import os
import tkinter as tk
from tkinter import filedialog
import glob2  # pip install glob2
from PIL import Image, ImageEnhance, ImageOps  # pip install pillow


def get_photo_brightness(image_path):
    # 加载图像
    image = Image.open(image_path)
    # 转换为灰度图像
    gray_image = image.convert("L")
    # 计算图像亮度
    brightness = sum(gray_image.getdata()) / len(gray_image.getdata())
    # 输出结果
    print("图像亮度：", brightness)
    return brightness;


def get_camera_parameters(image_path):
    try:
        # 打开图像文件
        with Image.open(image_path) as img:
            # 获取 Exif 数据
            exif_data = img._getexif()

            # 如果存在 Exif 数据
            if exif_data is not None:
                # 获取相机制造商和型号
                make = exif_data.get(271)
                model = exif_data.get(272)

                # 获取曝光时间
                exposure_time = exif_data.get(33434)

                # 获取光圈值
                aperture_value = exif_data.get(33437)

                # 获取焦距
                focal_length = exif_data.get(37386)

                # 获取亮度值
                brightness_value = exif_data.get(37379)  # 0x9203

                # 返回相机参数
                return {
                    "make": make,
                    "model": model,
                    "exposure_time": exposure_time,
                    "aperture_value": aperture_value,
                    "focal_length": focal_length,
                    "brightness_value": brightness_value
                }

            else:
                return None

    except (IOError, ValueError):
        return None


def list_image_files(directory):
    image_extensions = ["*.jpg", "*.jpeg", "*.png", "*.gif"]
    image_files = []
    for extension in image_extensions:
        pattern = os.path.join(directory, extension)
        image_files.extend(glob2.glob(pattern))
    return image_files


bright_ok_mean = 0.0
img_todo_dict = {}


def do_bright():
    for key, value in img_todo_dict.items():
        brightness_rate = bright_ok_mean / value
        image = Image.open(key)
        image_info = ImageOps.exif_transpose(image)
        if image.size != image_info.size:
            image = image.rotate(270, expand=1)
        enhancer = ImageEnhance.Brightness(image)
        bright_image = enhancer.enhance(brightness_rate)
        img_dir = os.path.dirname(key)
        img_name = os.path.basename(key)
        img_dir_new = os.path.join(img_dir, 'brightness_out')
        if not os.path.exists(img_dir_new):
            os.mkdir(img_dir_new)
        img_path = os.path.join(img_dir_new, img_name)
        bright_image.save(img_path)


def choose_directory():
    directory = filedialog.askdirectory()
    label.config(text="选择的目录：" + directory)
    image_files = list_image_files(directory)
    bright_arr = []
    for image_file in image_files:
        print(image_file)
        photo_data = get_camera_parameters(image_file)
        print(photo_data)
        if photo_data is None:
            continue
        brightness = get_photo_brightness(image_file)
        if photo_data["brightness_value"] is None \
                or photo_data["brightness_value"] < 0:
            img_todo_dict[image_file] = brightness
        else:
            bright_arr.append(brightness)
    global bright_ok_mean
    bright_ok_mean = sum(bright_arr) / len(bright_arr)
    print(bright_ok_mean)


root = tk.Tk()
root.geometry("400x600")
root.title("目录选择器")

label = tk.Label(root, text="选择的目录：")
label.pack(pady=20)

button = tk.Button(root, text="选择目录", command=choose_directory)
button.pack(pady=10)

button_do = tk.Button(root, text="增亮照片", command=do_bright)
button_do.pack(side="bottom", pady=50)

root.mainloop()
